﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SmartSpace.UI.Silverlight;
using SmartSpace.UI.Silverlight.Dynamic.DynamicRef;
using System.ServiceModel;

namespace SmartSpace.UI.Silverlight.Dynamic
{
    public class DynamicModule : AppModule
    {
        private static string s_hostUrl;

        /// <summary>
        /// silverlight 所在的网站地址
        /// </summary>
        public static string HostUrl
        {
            get
            {
                if (string.IsNullOrEmpty(s_hostUrl))
                {
                    string sourcePath = Application.Current.Host.Source.AbsoluteUri.ToUpper();
                    string absolutePath = Application.Current.Host.Source.AbsolutePath.ToUpper();
                    if (absolutePath.StartsWith("/CLIENTBIN"))
                    {
                        s_hostUrl = sourcePath.Replace(absolutePath, "/");
                    }
                    else
                    {
                        // ex: /WebSite/ClientBin/DemeterSoft.Shell.xap
                        // 含有虚拟目录
                        string[] subs = absolutePath.Split(new string[] { "/CLIENTBIN" }, StringSplitOptions.RemoveEmptyEntries);
                        absolutePath = absolutePath.Replace(subs[0], string.Empty);
                        s_hostUrl = sourcePath.Replace(absolutePath, "/");
                    }
                }
                return s_hostUrl;
            }
        }

        public DynamicModule()
            : base(new Guid("{6B9F8722-3832-4C6D-BC82-657F37CD1E57}"), "Dynamic module")
        {
        }

        public static DynamicWebServiceSoapClient CreateProxy()
        {
            System.ServiceModel.Channels.Binding binding = new System.ServiceModel.BasicHttpBinding();
            (binding as BasicHttpBinding).MaxBufferSize = 2147483647;
            (binding as BasicHttpBinding).MaxReceivedMessageSize = 2147483647;
            DynamicWebServiceSoapClient client = new DynamicWebServiceSoapClient(binding, new EndpointAddress(HostUrl + "DynamicWebService.asmx"));
            return client;
        }
    }
}
